Python Program to Find Factors of a Number | Using for loop, while loop & function

Python Program to Find Factors of a Number | Using for loop, while loop & function

Python Program to Find Factors

The numbers which are completely divisible by the given value(remainder is 0) called as factors of a given number in C.

Example: Factors of 20 = 1,2,4,5,10,20.

Factors of 36 = 1,2,3,4,6,9,12,18,36.

In this example, you will learn to find all the factors of an number entered by the user using for loop, while loop, function & if statement in Python programming.


Program to Find Factors of a Number

Using for loop:

x = int(input("Please Enter any Number: "))
print("The factors of",x,"are: ")
for i in range(1, x + 1): #for loop
    if x % i == 0:
        print(i)


Using while loop:

number = int(input("Please Enter any Number: "))
value = 1
print("Factors of {0} are:".format(number))
while (value <= number): #While loop
    if(number % value == 0):
        print("{0}".format(value))
    value = value + 1


Using function:

def print_factors(x): #function for find factors
   print("The factors of",x,"are:")
   for i in range(1, x + 1):
       if x % i == 0:
           print(i)
num = int(input("Please Enter any Number: "))
print_factors(num) #function call

Output:
Enter a number to Find Factors 36 Factors of the Given Number are: 1 2 3 4 6 9 12 18 36
Enter a number to Find Factors 20
Factors of the Given Number are: 1  2  4  5  10  20
Enter a number to Find Factors 49 Factors of the Given Number are: 1 7 49

Run Code- If you want run this code copy this code, paste here and run.



No comments: